<template>
	<view class="container">
		<view class="title">欢迎登录灰耳朵宠物陪护</view>
		<template v-if="loginType == 'verify'">
			<view class="tips">
				<text class="dot"></text>
				<text>未注册过的手机号验证后将自动注册</text>
			</view>

			<!-- 验证码登录表单内容 -->
			<view class="input-group">
				<view class="country-code">+{{ loginInfo.areaCode }}</view>
				<input type="number" v-model="loginInfo.phone" placeholder="请输入手机号" maxlength="11" class="input" />
				<view class="input-group-fixed">
					<uni-icons class="clear-icon" v-show="loginInfo.phone" @click="loginInfo.phone = ''" type="closeempty" size="20"></uni-icons>
				</view>
			</view>
			<view class="input-group">
				<input type="number" v-model="loginInfo.verifyCode" placeholder="请输入验证码" maxlength="6"
					class="input" />
				<view class="input-group-fixed">
					<uni-icons class="clear-icon" v-show="loginInfo.verifyCode" @click="loginInfo.verifyCode = ''" type="closeempty" size="20"></uni-icons>
					<view class="verify-btn"
						:style="verifyBtnStyle" @click="loginInfo.getVerifyCode">
						{{ countdownText }}
					</view>
				</view>
			</view>
			<view class="clickyzm">
				没收到验证码？
				<text class="link" @click="showHelpPopup = true">请点击</text>
			</view>
			<view v-if="registerFun.isShow" class="input-group xjs-mt-24" @tap="registerFun.openRefereePop">
				<input type="text" disabled v-model="registerFun.refereeCode" placeholder="填写推荐人" class="input" />
				<view class="input-group-fixed">
					<view class="confirm-btn xjs-btn-primary">{{registerFun.refereeCode?'修改':'填写'}}</view>	
				</view>
			</view>
		</template>
		<template v-else>
			<!-- 验证码登录表单内容 -->
			<view class="input-group">
				<view class="country-code">+{{ loginInfo.areaCode }}</view>
				<input type="number" v-model="loginInfo.phone" placeholder="请输入手机号" maxlength="11" class="input" />
				<view class="input-group-fixed">
					<uni-icons class="clear-icon" v-show="loginInfo.phone" @click="loginInfo.phone = ''" type="closeempty" size="20"></uni-icons>
				</view>
			</view>
		</template>
		<!-- 协议勾选 -->
		<view class="agreement">
			<image class="checkbox-icon" :src="
					isAgree
						? 'https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-13.png'
						: 'https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-12.png'
				" @click="isAgree = !isAgree" />
			<text class="agreement-text">
				我已阅读并同意
				<text @click="toUserAgree('/pages/setting/userAgreement/index')" class="link">《灰耳朵宠物陪护用户服务协议》</text>
				和
				<text @click="toUserAgree('/pages/setting/privacyAgreement/index')" class="link">《灰耳朵宠物隐私政策》</text>
			</text>
		</view>
		<template v-if="loginType == 'verify'">
			<button v-if="registerFun.isShow" class="submit-btn xjs-btn-primary" @click="registerFun.handleSubmit">注册</button>
			<button v-else class="submit-btn xjs-btn-primary" @click="loginInfo.handleSubmit">确定</button>
		</template>
		<button v-else class="submit-btn xjs-btn-primary" @click="loginInfo.passwordSubmit">确定</button>
		<view v-if="loginType == 'verify'" @click="loginType = 'password'" class="login-type">密码登录</view>
		<view v-else @click="loginType = 'verify'" class="login-type">验证码登录</view>
		<!-- 验证码帮助弹框 -->
		<uni-popup ref="popup" type="bottom" @change="popupChange" background-color="#fff"
			border-radius="32rpx 32rpx 0 0">
			<view class="popup-content">
				<view class="popup-title">
					<text>收不到验证码？</text>
					<text class="close-icon" @click="showHelpPopup = false">×</text>
				</view>
				<view class="help-list">
					<view class="help-item">1. 请确认手机无欠费、停机以及网络不畅的情况；</view>
					<view class="help-item">2. 打开短信垃圾箱，查看验证码是否被拦截；</view>
					<view class="help-item">3. 请确认当前使用的手机号码与注册手机号是否一致；</view>
					<view class="help-item">4. 运营商短信通道延迟，请耐心等候或重新获取验证码；</view>
				</view>
				<button class="xjs-btn-primary" @click="showHelpPopup = false">好的</button>
			</view>
		</uni-popup>
		<!-- 输入密码弹框 -->
		<uni-popup ref="passwordRef" type="bottom" @change="passwordChange" background-color="#fff"
			border-radius="32rpx 32rpx 0 0">
			<view class="popup-content">
				<view class="popup-title">
					<text>请输入密码</text>
					<text class="close-icon" @click="showPassword = false">×</text>
				</view>
				<view class="input-group">
					<input :password='!loginInfo.iseye' type="text" v-model="loginInfo.password" placeholder="请输入密码" class="input" />
					<view class="input-group-fixed">
						<uni-icons class="clear-icon" v-show="loginInfo.password" @click="loginInfo.password = ''" type="closeempty" size="20"></uni-icons>
						<uni-icons class="eye-icon" @click="loginInfo.iseye = !loginInfo.iseye" :type="loginInfo.iseye ? 'eye' : 'eye-slash'" size="22"></uni-icons>
					</view>
				</view>
				<view
					@click="toUserAgree(`/pages/login/verifyPhone?phone=${loginInfo.phone}&userId=${loginInfo.userId}`)"
					class="forget">忘记密码</view>
				<button class="xjs-btn-primary" @click="loginInfo.passwordSubmitAgain">登录</button>
			</view>
		</uni-popup>
		
		<!-- 注册显示推荐人弹框 -->
		<uni-popup ref="registerRef" type="center" background-color="#fff" border-radius="32rpx 32rpx 32rpx 32rpx"
			:mask-click="false">
			<view class="register-popup-content">
				<view class="popup-title">请确认你的邀请人</view>
				<view class="popup-info">
					<text class="info-label">邀请人来自"{{ registerFun.refereeInfo.studioName }}"</text>
					<view class="info-card">
						<image class="avatar" :src="registerFun.refereeInfo.avatar" mode="aspectFill" />
						<view class="info">
							<view class="name xjs-line-one">{{ registerFun.refereeInfo.nickName }}</view>
							<view class="id">ID {{ registerFun.refereeInfo.id }}</view>
						</view>
					</view>
				</view>
				<view class="popup-btns">
					<view class="btn-flex xjs-btn-primary-plain" @tap="registerFun.closePopup">错了，重新填写</view>
					<view class="btn-flex xjs-btn-primary" @tap="registerFun.againSubmit">确认</view>
				</view>
			</view>
		</uni-popup>
		<!-- 填写推荐人弹框 -->
		<uni-popup ref="checkRefereeRef" type="center" background-color="#fff" border-radius="32rpx 32rpx 32rpx 32rpx">
			<view class="register-popup-content">
				<view class="popup-title">请填写推荐人</view>
				<view class="input-group xjs-mt-24">
					<input type="text" v-model="registerFun.refereeCodePop" placeholder="请输入推荐人id" class="input" />
					<view class="input-group-fixed">
						<view class="confirm-btn xjs-btn-primary" @tap="registerFun.checkInfo">确定</view>	
					</view>
				</view>
				<template v-if="registerFun.refereeInfo.id">
					<view class="popup-info">
						<text class="info-label">邀请人来自"{{ registerFun.refereeInfo.studioName }}"</text>
						<view class="info-card">
							<image class="avatar" :src="registerFun.refereeInfo.avatar" mode="aspectFill" />
							<view class="info">
								<view class="name xjs-line-one">{{ registerFun.refereeInfo.nickName }}</view>
								<view class="id">ID {{ registerFun.refereeInfo.id }}</view>
							</view>
						</view>
					</view>
					<view class="popup-btns">
						<view class="xjs-btn-primary" @tap="checkRefereeRef.close()">确认</view>
					</view>
				</template>
				<!-- <view class="popup-title">请填写推荐人</view>
				<view class="input-group xjs-mt-24">
					<input type="text" v-model="registerFun.refereeCode" placeholder="请输入推荐人id" class="input" />
					<view class="input-group-fixed">
						<view class="confirm-btn xjs-btn-primary" @tap="registerFun.checkInfo">确定</view>	
					</view>
				</view>
				<view v-if="registerFun.refereeInfo.id" class="popup-btns">
					<view class="xjs-btn-primary" @tap="checkRefereeRef.close()">确认</view>
				</view> -->
			</view>
		</uni-popup>
	</view>
</template>

<script setup lang="ts">
	import { onLoad } from '@dcloudio/uni-app';
	import { ref, computed, watch, reactive } from 'vue';
	import { useLogin, isRegisterUser, useLoginPassword } from '@/hooks/useLogin';
	import { useUserStoreToRefs } from '@/store/useUserStore'
	const { shareRefereeId } = useUserStoreToRefs()
	import api from '@/api';
	onLoad((params) => {
		//只有用户切换账号才需要带这些参数进入此页面
		// 注册方式：0-第一次登录注册，1-切换账号时选择新手机号注册，2-切换账号时选择当前手机号再注册账号
		loginInfo.registerWay = params.registerWay || 0
		loginInfo.phone = params.phone || ''
		loginInfo.areaCode = params.areaCode || '86'
		registerFun.refereeCode = shareRefereeId.value || ''
	})
	// 弹框状态
	const showHelpPopup = ref(false);
	const popupChange = (e : { show : boolean }) => {
		if (!e.show) {
			showHelpPopup.value = false;
		}
	};
	const popup = ref();
	watch(showHelpPopup, (newVal) => {
		if (newVal) {
			popup.value.open();
		} else {
			popup.value.close();
		}
	});
	// 弹框状态-密码
	const showPassword = ref(false);
	const passwordChange = (e : { show : boolean }) => {
		if (!e.show) {
			showPassword.value = false;
		}
	};
	const passwordRef = ref();
	watch(showPassword, (newVal) => {
		if (newVal) {
			passwordRef.value.open();
		} else {
			passwordRef.value.close();
		}
	});
	// 是否可以获取验证码
	const canGetCode = computed(() => {
		return loginInfo.phone.length >= 4;
	});

	// 获取验证码按钮文本颜色
	const verifyBtnStyle = computed(() => {
		return {
			color: canGetCode && !loginInfo.isCountdown ? 'var(--color-primary)' : '#999'
		};
	});
	// 获取验证码按钮文本
	const countdownText = computed(() => {
		return loginInfo.isCountdown ? `重新获取(${loginInfo.countdown}s)` : '获取验证码';
	});
	// 登录类型：verify-验证码登录，password-密码登录
	const loginType = ref('verify');
	const loginInfo = reactive<any>({
		areaCode: '86',
		phone: '',
		verifyCode: '',
		isCountdown: false,
		countdown: 0,
		password: "",
		userId: "",
		registerWay: 0,
		iseye:false,
		passwordSubmitAgain: async () => {
			let blankSpaceReg = /^\S*$/; //非空格正则
			let loginPswReg = /^.{6,20}$/; //密码正则
			let notzhongwen = /^[^\u4e00-\u9fa5]+$/
			if (!loginInfo.password) {
				uni.showToast({
					title: '密码不能为空',
					icon: 'none'
				});
				return;
			}
			if (!blankSpaceReg.test(loginInfo.password)) {
				uni.showToast({
					title: '密码中不可输入空格',
					icon: 'none'
				});
				return;
			}
			if (!loginPswReg.test(loginInfo.password) || !notzhongwen.test(loginInfo.password)) {
				uni.showToast({
					title: '密码错误，请重新输入',
					icon: 'none'
				});
				return;
			}
			useLoginPassword({
				mobile: loginInfo.phone,
				password: loginInfo.password,
				countryCode: loginInfo.areaCode,
				userId: loginInfo.userId,
				step: 3
			});
			showPassword.value = false;
		},
		passwordSubmit: async () => {
			let phoneReg = /^1[3456789]\d{9}$/; //手机号正则
			// 校验手机号
			if (!loginInfo.phone) {
				uni.showToast({
					title: '手机号码不能为空',
					icon: 'none'
				});
				return;
			}
			if (!phoneReg.test(loginInfo.phone)) {
				uni.showToast({
					title: '手机号码有误',
					icon: 'none'
				});
				return;
			}
			// 公共校验 - 协议
			if (!isAgree.value) {
				uni.showToast({
					title: '请阅读并同意用户协议和隐私政策',
					icon: 'none'
				});
				return;
			}
			// TODO: 调用密码登录接口
			let phoneRes : any = await isRegisterUser(loginInfo.phone,loginInfo.registerWay);
			if (phoneRes.data.length == 0) {
				uni.showModal({
					title: '提示',
					content: '手机号不存在，请重新输入或验证码登录',
					confirmText: '重新输入',
					cancelText: '切换验证',
					success: (res) => {
						if (res.confirm) {
						} else if (res.cancel) {
							loginType.value = 'verify';
						}
					}
				});
				return;
			}
			if (phoneRes.data.length == 1) {
				showPassword.value = true
				loginInfo.userId = phoneRes.data[0].id;
				return
			}
			if (phoneRes.data.length > 1) {
				uni.navigateTo({
					url: `/pages/login/account?phone=${loginInfo.phone}&password=password&areaCode=${loginInfo.areaCode}`
				});
				return;
			}
		},
		handleSubmit: async () => {
			let phoneReg = /^1[3456789]\d{9}$/; //手机号正则
			// 校验手机号
			if (!loginInfo.phone) {
				uni.showToast({
					title: '手机号码不能为空',
					icon: 'none'
				});
				return;
			}
			if (!phoneReg.test(loginInfo.phone)) {
				uni.showToast({
					title: '手机号码有误',
					icon: 'none'
				});
				return;
			}
			if (!loginInfo.verifyCode) {
				uni.showToast({
					title: '请输入验证码',
					icon: 'none'
				});
				return;
			}
			// TODO: 调用验证码登录接口
			let phoneRes : any = await isRegisterUser(loginInfo.phone,loginInfo.registerWay);
			let userId = '';
			registerFun.isShow = false
			if (phoneRes.data.length == 1) {
				userId = phoneRes.data[0].id;
			} else if (phoneRes.data.length > 1) {
				uni.navigateTo({
					url: `/pages/login/account?phone=${loginInfo.phone}&verifyCode=${loginInfo.verifyCode}&areaCode=${loginInfo.areaCode}`
				});
				return;
			} else {
				registerFun.isShow = true
				// uni.navigateTo({
				// 	url: `/pages/login/refereeCode?phone=${loginInfo.phone}&verifyCode=${loginInfo.verifyCode}&areaCode=${loginInfo.areaCode}&registerWay=${loginInfo.registerWay}`
				// });
				return;
			}
			// 协议
			if (!isAgree.value) {
				uni.showToast({
					title: '请阅读并同意用户协议和隐私政策',
					icon: 'none'
				});
				return;
			}
			useLogin({
				mobile: loginInfo.phone,
				code: loginInfo.verifyCode,
				countryCode: loginInfo.areaCode,
				userId: userId,
				step: 3
			});
		},
		getVerifyCode: async () => {
			if (loginInfo.isCountdown || !canGetCode.value) return;
			if (!loginInfo.phone) {
				uni.showToast({
					title: '请输入手机号',
					icon: 'none'
				});
				return;
			}
			// 校验是否为数字
			if (!/^\d+$/.test(loginInfo.phone)) {
				uni.showToast({
					title: '手机号只能输入数字',
					icon: 'none'
				});
				return;
			}
			// 开始倒计时
			loginInfo.countdown = 60;
			loginInfo.isCountdown = true;
			const timer = setInterval(() => {
				loginInfo.countdown--;
				if (loginInfo.countdown <= 0) {
					clearInterval(timer);
					loginInfo.isCountdown = false;
				}
			}, 1000);
			let phoneRes : any = await isRegisterUser(loginInfo.phone,loginInfo.registerWay);
			let yzmApi = `/mobile/code/v2?mobile=${loginInfo.phone}&type=login&countryCode=${loginInfo.areaCode}&isVoiceCode=0&sourceType=1`;
			if (phoneRes.data.length == 0) {
				// 账号没注册用注册的发送验证码
				yzmApi = `/mobile/code/v2?mobile=${loginInfo.phone}&type=register&countryCode=${loginInfo.areaCode}&isVoiceCode=0&sourceType=1`;
			}
			// API调用
			const res : any = await api({
				method: 'get',
				url: yzmApi
			});
			
			if (res.code !== 0) {
				clearInterval(timer);
				loginInfo.isCountdown = false;
				loginInfo.countdown = 0;
				uni.showToast({
					icon: 'none',
					mask: true,
					title: res.msg
				});
				return;
			} else {
				uni.showToast({
					icon: 'none',
					mask: true,
					title: '验证码已发送，请注意查收'
				});
				//校验手机号后直接先判断手机号是否注册过
				let phoneRes : any = await isRegisterUser(loginInfo.phone,loginInfo.registerWay);
				if (phoneRes.data.length == 0) {
					registerFun.isShow = true
				}else{
					registerFun.isShow = false
				}
			}
		}
	});
	
	const registerRef = ref()
	const checkRefereeRef = ref()
	const registerFun = reactive<any>({
		isShow:false,
		refereeCode:"",
		refereeCodePop:"",
		refereeInfo:{},
		checkInfo:async()=>{
			registerFun.refereeInfo = {}
			if (!registerFun.refereeCodePop){
				uni.showToast({
					icon: 'none',
					title: '请填写推荐人' 
				});
				return
			}
			const res : any = await api({
				method: 'get',
				url: `/mall/user/inviter/${registerFun.refereeCodePop}`
			});
			console.log(registerFun.refereeCodePop)
			console.log(res)
			if (!res.data) {
				uni.showToast({
					icon: 'none',
					title: '推荐人不存在，请重新输入'
				});
				return;
			}
			// （0-陪宠师 1-店长 2-普通用户）
			if (res.data.identity == 2) {
				uni.showToast({
					icon: 'none',
					title: '此用户无推荐权限，请重新输入'
				});
				return;
			}
			registerFun.refereeInfo = res.data
			registerFun.refereeCode = registerFun.refereeCodePop
		},
		openRefereePop:()=>{
			checkRefereeRef.value.open()
			registerFun.refereeCodePop = registerFun.refereeCode
		},
		closePopup:()=>{
			registerRef.value.close();
		},
		againSubmit:async()=>{
			// TODO: 处理确认逻辑 - 手机号验证码注册
			const res : any = await api({
				method: 'post',
				url: `/mall/user/v2/register-login/v2`,
				data: {
					code: loginInfo.verifyCode,
					mobile: loginInfo.phone,
					refereeId: registerFun.refereeInfo.id,
					countryCode: loginInfo.areaCode,
					openId: '',
					origin: 0,
					userId: '',
					// 注册方式：0-第一次登录注册，1-切换账号时选择新手机号注册，2-切换账号时选择当前手机号再注册账号
					registerWay: loginInfo.registerWay
				}
			});
			if (res.code == 1) {
				uni.showToast({
					icon: 'none',
					title: res.msg
				});
				return;
			}
			if (res.code == 0) {
				useLogin({
					mobile: loginInfo.phone,
					code: loginInfo.verifyCode,
					countryCode: loginInfo.areaCode,
					userId: res.data[0].id,
					step: 3
				}, () => {
					uni.navigateTo({
						url: `/pages/login/settingPassword?phone=${loginInfo.phone}&areaCode=${loginInfo.areaCode}&userId=${res.data[0].id}&register=register`
					})
				})
				registerFun.closePopup()
			}
		},
		handleSubmit:async ()=>{
			if (!isAgree.value) {
				uni.showToast({
					title: '请阅读并同意用户协议和隐私政策',
					icon: 'none'
				});
				return;
			}
			if (!registerFun.refereeCode){
				uni.showToast({
					icon: 'none',
					title: '请填写推荐人'
				});
				return
			}
			const res : any = await api({
				method: 'get',
				url: `/mall/user/inviter/${registerFun.refereeCode}`
			});
			if (!res.data) {
				uni.showToast({
					icon: 'none',
					title: '推荐人不存在，请重新输入'
				});
				return;
			}
			// （0-陪宠师 1-店长 2-普通用户）
			if (res.data.identity == 2) {
				uni.showToast({
					icon: 'none',
					title: '此用户无推荐权限，请重新输入'
				});
				return;
			}
			registerFun.refereeInfo = res.data
			registerRef.value.open();
		}
	})
	// 是否同意协议
	const isAgree = ref(false);
	const toUserAgree = (url) => {
		uni.navigateTo({
			url: url
		});
	};
</script>

<style lang="scss" scoped>
	.container {
		padding: 120rpx 48rpx 48rpx;
		min-height: 100vh;
		background-color: #fff;
		box-sizing: border-box;

		.title {
			font-size: 40rpx;
			font-weight: bold;
			text-align: center;
			margin-bottom: 80rpx;
		}

		.tips {
			font-size: 24rpx;
			color: var(--color-primary);
			text-align: left;
			margin-bottom: 24rpx;
			display: flex;
			align-items: center;
			gap: 8rpx;

			.dot {
				width: 8rpx;
				height: 8rpx;
				background-color: var(--color-primary);
				border-radius: 50%;
				display: inline-block;
			}
		}

		.clickyzm {
			text-align: right;
			font-size: 24rpx;
			color: #999;

			.link {
				color: var(--color-primary);
			}
		}

		.login-type {
			text-align: center;
			font-size: 30rpx;
			color: #333;
		}

		.popup-content {
			background-color: #fff;
			border-radius: 24rpx 24rpx 0 0;
			padding: 40rpx;

			.popup-title {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 40rpx;
				font-size: 32rpx;
				font-weight: 500;

				.close-icon {
					font-size: 48rpx;
					color: #333;
					line-height: 1;
				}
			}

			.help-list {
				.help-item {
					font-size: 28rpx;
					color: #666;
					line-height: 1.6;
					margin-bottom: 24rpx;

					&:last-child {
						margin-bottom: 40rpx;
					}
				}
			}

			.forget {
				margin: 24rpx 0;
				text-align: right;
				font-size: 24rpx;
				color: #666;
			}
		}

		.agreement {
			display: flex;
			align-items: center;
			margin: 80rpx 0;

			.checkbox-icon {
				width: 32rpx;
				height: 32rpx;
				flex-shrink: 0;
			}

			.agreement-text {
				font-size: 24rpx;
				color: #666;
				margin-left: 16rpx;
			}

			.link {
				color: var(--color-primary);
			}
		}

		.submit-btn {
			margin: 40rpx 0;
		}
		
		.register-popup-content {
			width: 600rpx;
			padding: 48rpx 32rpx;
			box-sizing: border-box;
			border-radius: 24rpx;
			overflow: hidden;
		
			.popup-title {
				font-size: 32rpx;
				color: #333;
				text-align: center;
				font-weight: bold;
				margin-bottom: 48rpx;
			}
		
			.popup-info {
				background-color: #f5f6f7;
				padding: 32rpx;
				border-radius: 16rpx;
				margin-bottom: 48rpx;
		
				.info-label {
					font-size: 26rpx;
					color: #1b2120;
					margin-bottom: 16rpx;
					display: block;
					border-bottom: 1rpx solid #e4e6e6;
					padding-bottom: 6rpx;
				}
		
				.info-card {
					display: flex;
					align-items: center;
					padding-top: 32rpx;
		
					.avatar {
						width: 96rpx;
						height: 96rpx;
						border-radius: 50%;
						margin-right: 16rpx;
						flex-shrink: 0;
					}
		
					.info {
						flex: 1;
		
						.name {
							width: 350rpx;
							font-size: 32rpx;
							color: #333;
							margin-bottom: 4rpx;
							font-weight: bold;
						}
		
						.id {
							font-size: 26rpx;
							color: #7c807f;
						}
					}
				}
			}
		
			.popup-btns {
				display: flex;
				justify-content: space-between;
				gap: 24rpx;
				.btn-flex{
					flex: 1;
				}
			}
		}
	}
</style>